#!/usr/bin/env python
# School-Admin


###########################################################################
# 
#  Copyright (C) 2007 Sarath Lakshman. All rights reserved.
# 
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################


import sys,shelve,settings,os
from PyQt4 import QtGui,QtCore

filedata=[('Admission No','admno'), ('Name of Pupil','name'), ('Name of village/Town', 'hname'), ('Name of Parent','pname'), ('Name of Guardian','gname'), ('Residence', 'resdance'), ('Occupation of Parent/Guardian', 'occupation'), ('School & Class from which coming', 'schoolclass'), ('Whether a T.C from a Secondary school produced','tcprod'), ('Date of Admission', 'dateadm'), ('Date of Birth','db'), ('Whether Protected from Smallpox or not','protsmallpox'), ('Nationality', 'nationality'), ('Religion','religion'), ('Does the pupil belonging to SC/ST or convert from SC', 'sc'), ('Mothertongue of Pupil', 'lang'), ('Class on Admission', 'classadmission'), ('No and date of T.C produced', 'nodattc'), ('Class on leaving','classleav'), ('Date of leaving', 'dateleav'), ('No and Date of T.C issued', 'nodatetc'), ('Reason for leaving', 'reason'), ('School to which Pupil has gone', 'pupilgo')]



#set working directory to app.py directory
wrk_path=os.path.split(sys.argv[0])[0]
if wrk_path!='':
	os.chdir(wrk_path)



class thestudent_app(QtGui.QMainWindow):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.setWindowTitle("Student Admission Register")

		self.statusmessage("Welcome !")

		self.resize(600,450)

		self.center()

		self.setWindowIcon(QtGui.QIcon("pics/logo.png"))


		# Details on content

		
		self.fileddata=filedata



		# Menu and related items
		
		menus=self.menuBar()

		exit=QtGui.QAction("Exit",self)
		self.connect(exit,QtCore.SIGNAL('triggered()'),QtCore.SLOT('close()'))

		main_widget=QtGui.QAction("Home",self)
		self.connect(main_widget,QtCore.SIGNAL('triggered()'),self.homepage_function)
		
		editor=QtGui.QAction("Entry Editor",self)
		self.connect(editor,QtCore.SIGNAL('triggered()'),self.editor_menu_function)

		add=QtGui.QAction("Entry Adder",self)
		self.connect(add,QtCore.SIGNAL('triggered()'),self.add_menu_function)

		listing=QtGui.QAction("List Editor",self)
		self.connect(listing,QtCore.SIGNAL('triggered()'),self.list_menu_function)

		setting_item=QtGui.QAction("Administrative Settings ",self)
		self.connect(setting_item,QtCore.SIGNAL('triggered()'),self.settings_menu_function)


		aboutm=QtGui.QAction("About..",self)
		self.connect(aboutm,QtCore.SIGNAL('triggered()'),self.about_menu_function)

	
		
			
		file=menus.addMenu('&File')
		file.addAction(main_widget)
		file.addSeparator()
		file.addAction(exit)

		tool=menus.addMenu('&Tool')
		tool.addAction(add)
		tool.addAction(editor)
		tool.addAction(listing)

		setting_menu=menus.addMenu('&Settings')
		setting_menu.addAction(setting_item)
		
		about_menu=menus.addMenu('&Help')
		about_menu.addAction(aboutm)


		#Widget handle constants
		
		self.widget=0
		self.entryno=[1]

		#create settings dialog
		self.setting_window=settings.settings(self.entryno)
		self.setting_window.hide()


		#TAB BAR
		self.tabwidget=QtGui.QTabWidget(self)
		self.setCentralWidget(self.tabwidget)

		
		self.editpages()
		self.create_fields()
		
		#Hide Qwidgets created
		self.mainwidget.hide()
		self.mainwidget_part.hide()
		self.mainwidget_editor.hide()
		self.mainwidget_editor2.hide()
		

		

		self.entryno_last=( len(shelve.open(shelve.open('settings','c')['DB'],'c').keys()) - 1 )

		self.listing=printlist() ##################   temp  ######################
		#self.tabwidget.addTab(self.x,"Hello")

		class mainmenu(QtGui.QWidget):
			def __init__(self,f1,f2,f3,f4,f5,parent=None):
				QtGui.QWidget.__init__(self,parent)
				lbl=QtGui.QLabel("",self)
				lbl.setPixmap(QtGui.QPixmap("pics/backg.png"))
				btn1=QtGui.QPushButton("Register student",self)
				btn2=QtGui.QPushButton("Modify Entry",self)
				btn3=QtGui.QPushButton("Print List",self)
				btn4=QtGui.QPushButton("Settings",self)
				btn5=QtGui.QPushButton("About",self)
	
				btn1.move(170,144)
				btn1.setMinimumHeight(50)
				btn1.setMinimumWidth(120)


				btn2.move(300,144)
				btn2.setMinimumHeight(50)
				btn2.setMinimumWidth(120)

				btn3.move(170,200)
				btn3.setMinimumHeight(50)
				btn3.setMinimumWidth(120)

				btn4.move(300,200)
				btn4.setMinimumHeight(50)
				btn4.setMinimumWidth(120)	

				btn5.move(235,255)
				btn5.setMinimumHeight(50)
				btn5.setMinimumWidth(120)			
				self.connect(btn1,QtCore.SIGNAL('clicked()'),f1)
				self.connect(btn2,QtCore.SIGNAL('clicked()'),f2)
				self.connect(btn3,QtCore.SIGNAL('clicked()'),f3)
				self.connect(btn4,QtCore.SIGNAL('clicked()'),f4)
				self.connect(btn5,QtCore.SIGNAL('clicked()'),f5)


		#Add Home Page in starting to TAB

		self.main_firstshown=mainmenu(self.add_menu_function,self.editor_menu_function,self.list_menu_function,self.settings_menu_function,self.about_menu_function)

		self.about_dialog=about()
		self.about_dialog.hide()

		self.homepage_function()
		
		
	
	def settings_menu_function(self):
		self.setting_window.show()
		self.setting_window.do_password_check()	

	def about_menu_function(self):
		self.about_dialog.show()
				

	def statusmessage(self,message):
		self.timerno=1
		self.message=message
		self.timer=QtCore.QTimer(self)
		self.timer.start(600)
		self.connect(self.timer,QtCore.SIGNAL('timeout()'),self.timer_action)
			
		

	def timer_action(self):
		if self.timerno==1:
			self.statusBar().showMessage(self.message)
			self.timerno=2		
		elif self.timerno==2:
			self.statusBar().showMessage(" ")
			self.timerno=3
		elif self.timerno==3:
			self.statusBar().showMessage(self.message)
			self.timerno=4
		elif self.timerno==4:
			self.statusBar().showMessage(" ")
			self.timer.stop()

	def center(self):
		screen=QtGui.QDesktopWidget().screenGeometry()
		size=self.geometry()
		self.move((screen.width() - size.width())/2,(screen.height() - size.height())/2)


	def create_fields(self):
		
	

		self.textboxnames=[]

		self.mainwidget=QtGui.QWidget(self)  ## QWidget 1


		tablayout=QtGui.QGridLayout()
		tabmainlayout=QtGui.QVBoxLayout()
		
		tab_btn=QtGui.QHBoxLayout()
		tab_btn.addStretch(1)

		
		''' ######################################## First page Starts here #########################'''

		self.title=QtGui.QLabel("<h1>%s</h1>" %shelve.open('settings','c')['schoolname'])
		self.title.setAlignment(QtCore.Qt.AlignHCenter)


		nxt=QtGui.QPushButton("Next")
		btn_add=QtGui.QPushButton("Add to Database")
		btn_back=QtGui.QPushButton("Back")
		
		ds=self.fileddata[1][1]
		for i in range(12):
			lbl=QtGui.QLabel(self.fileddata[i][0])
			
			textedit=QtGui.QLineEdit("")
			textedit.setObjectName(self.fileddata[i][1])
			exec("self.%s = textedit" %(self.fileddata[i][1]))
			exec("self.connect(self.%s,QtCore.SIGNAL('returnPressed ()'),self.do_focusing)" %(self.fileddata[i][1]))
			
			

			tablayout.addWidget(lbl,i,0)
			tablayout.addWidget(textedit,i,1)
			
			i=i+1
		
		tab_btn.addWidget(nxt)
		tabmainlayout.addWidget(self.title)
		tabmainlayout.addLayout(tablayout)
		tabmainlayout.addLayout(tab_btn)
		
		
		self.mainwidget.setLayout(tabmainlayout)		



		

		self.connect(nxt,QtCore.SIGNAL("clicked()"),self.Next_buttonfunction)
		self.connect(btn_back,QtCore.SIGNAL("clicked()"),self.Back_buttonfunction)
		self.connect(btn_add,QtCore.SIGNAL("clicked()"),self.storage)
		
		'''###############################Second part of Widget #####################################'''
	

		page2_lbl=QtGui.QLabel("<h3>Page 2</h3>")
		page2_lbl.setAlignment(QtCore.Qt.AlignHCenter)
		
		
		btn_back.resize(30,70)
		
		btns_layout=QtGui.QHBoxLayout()
		btns_layout.addWidget(btn_back)
		btns_layout.addWidget(btn_add)
		btns_layout.setSpacing(10)


		self.mainwidget_part=QtGui.QWidget(self)     ## QWidget 2

		
		tablayout2=QtGui.QGridLayout()
		tabmainlayout2=QtGui.QVBoxLayout()
		
				
		for i in range(12,23):
			lbl=QtGui.QLabel(self.fileddata[i][0])
			
			textedit=QtGui.QLineEdit("")
			textedit.setObjectName(self.fileddata[i][1])
			exec("self.%s = textedit" %(self.fileddata[i][1]))
			self.connect(textedit,QtCore.SIGNAL("returnPressed ()"),self.do_focusing)


			tablayout2.addWidget(lbl,i,0)
			tablayout2.addWidget(textedit,i,1)
			
			i=i+1
		
			

		
		tabmainlayout2.addWidget(page2_lbl)
		tabmainlayout2.addLayout(tablayout2)
		tabmainlayout2.addLayout(btns_layout)
		tabmainlayout2.addStretch(1)
		tabmainlayout2.setSpacing(10)
		
	
		self.mainwidget_part.setLayout(tabmainlayout2)		
		
		
		
	def do_focusing(self):
			
			obj=str(QtCore.QObject(self).sender().objectName())
			focus=0

			for i in range(1,23):
				if obj==self.fileddata[i][1]:
					focus=i

			if (focus!=11 and focus!=22 ):
				exec("self.%s.setFocus()" %(self.fileddata[focus+1][1]))
	
			elif focus==11:
				self.Next_buttonfunction()
			elif focus==22:
				self.storage()
		

	def Next_buttonfunction(self):
		
		self.tabwidget.setCurrentIndex(1)
		self.nationality.setFocus()

	def Back_buttonfunction(self):
		self.tabwidget.setCurrentIndex(0)
		


	def storage(self):
		


		status_no=len(shelve.open(shelve.open('settings','c')['DB'],'c').keys())-1 # Find entry no
		
		
		status_to_write=str(status_no+1)

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		self.student_prof=[]

		blank=0

		for i in range(23):
			text=str(eval("self.%s.text()" %(self.fileddata[i][1])))
			if text.isspace() or text=='':
				blank=1

		def write():
			for i in range(23):
				text=str(eval("self.%s.text()" %(self.fileddata[i][1])))
				self.student_prof.append(text)
										
			db[status_to_write]=self.student_prof
			db.close()
		
			
			self.statusBar().showMessage("Done")

			self.Back_buttonfunction()
			
			#set text fields to blank
			for i in range(23):
				if i==0:
					self.admno.setText(str(int(self.admno.text())+1))
				else:
					eval("self.%s.setText('')" %(self.fileddata[i][1]))
				
			self.admno.setFocus()

			self.entryno_last=len(shelve.open(shelve.open('settings','c')['DB'],'c').keys())-1 # Find entry no
			
			#self.dataloader_editer()
			




		def datecheck(date):
			
			dt1=len(date.split('-'))
			dt2=len(date.split('/'))
			dt3=len(date.split('.'))

			if (dt1==3 or dt2==3  or dt3==3) :	
					
				date=date.replace('.','-')
				date=date.replace('/','-')

				if (int(date.split('-')[0]) not in range(1,32)):
					return 'wrong'
					
				elif (int(date.split('-')[1]) not in range(1,13)):
					return 'wrong'

				elif ( len(date.split('-')[2])!=2 and len(date.split('-')[2])!=4  ) :
					return 'wrong'



			else:
	
				return 'wrong'	
				



		if (datecheck(self.dateleav.text())=='wrong' or datecheck(self.dateadm.text())=='wrong' or datecheck(self.db.text())=='wrong'):
			QtGui.QMessageBox.warning(self,"Wrong Date format", "You might have entered wrong date fromat. Enter date in the format dd-mm-yyyy" ,"Ok")
		else:

			if blank==1:
				QtGui.QMessageBox.warning(self,"Partial filling", "You haven't completed filling all the fields" ,"Ok")

			else:

				self.dateleav.setText(self.dateleav.text().replace('.','-'))
				self.dateleav.setText(self.dateleav.text().replace('/','-'))
				self.dateadm.setText(self.dateadm.text().replace('.','-'))
				self.dateadm.setText(self.dateadm.text().replace('/','-'))
				self.db.setText(self.db.text().replace('.','-'))
				self.db.setText(self.db.text().replace('/','-'))
				write()




	def editpages(self):
		
		############################## Page 1 ############################ 
		content_page1_label=QtGui.QLabel("<h2>Edit Contents</h2>")
		content_page1_label.setAlignment(QtCore.Qt.AlignHCenter)
		
		#entry_box=QtGui.QGroupBox("Entries")
		self.btn_entry_back=QtGui.QPushButton("Back")
		self.btn_entry_next=QtGui.QPushButton("Next")
		self.btn_entry_search=QtGui.QPushButton("Search")
		self.btn_entry_list=QtGui.QPushButton("Add to list")		
	
		self.btn_entry_search.setGeometry(self.btn_entry_search.geometry().left(),self.btn_entry_search.geometry().top(),90,90)


		self.btn_entry_back.setEnabled(False)
		
		self.connect(self.btn_entry_back,QtCore.SIGNAL('clicked()'),self.editor_back)
		self.connect(self.btn_entry_next,QtCore.SIGNAL('clicked()'),self.editor_next)
		self.connect(self.btn_entry_search,QtCore.SIGNAL('clicked()'),self.searchbar)
		self.connect(self.btn_entry_list,QtCore.SIGNAL('clicked()'),self.add_list)


		entry_layout=QtGui.QHBoxLayout()
		entry_layout2=QtGui.QHBoxLayout()
		entry_layout.addWidget(self.btn_entry_back)
		entry_layout.addWidget(self.btn_entry_next)
		entry_layout.addWidget(self.btn_entry_search)


		lbl=QtGui.QLabel("")

		entry_layout2.addWidget(self.btn_entry_list)
		entry_layout2.addWidget(lbl)
		
		

		self.mainwidget_editor=QtGui.QWidget(self)  #Qwidget for edit page1
		
		
		tab_editor_layout=QtGui.QGridLayout()

		vertical_editor_layout=QtGui.QVBoxLayout()
		
				
		for i in range(0,12):
			lbl=QtGui.QLabel(self.fileddata[i][0])
			
			textedit=QtGui.QLineEdit("")
			
			exec("self.%s = textedit" %(self.fileddata[i][1]+'_edit'))

			tab_editor_layout.addWidget(lbl,i,0)
			tab_editor_layout.addWidget(textedit,i,1)
			
			i=i+1
		
		
		vertical_editor_layout.addWidget(content_page1_label)
		vertical_editor_layout.addLayout(tab_editor_layout)
		vertical_editor_layout.addLayout(entry_layout) ## QGroupBox  ---Need EXTENSIONto Next button
		vertical_editor_layout.addLayout(entry_layout2)
		vertical_editor_layout.addStretch(1)
		tab_editor_layout.setSpacing(10)
		
	
		self.mainwidget_editor.setLayout(vertical_editor_layout)		
		
		
		
		########################### Page 2 #################################
	
		content_page2_label=QtGui.QLabel("<h4>Page 2</h4>")
		content_page2_label.setAlignment(QtCore.Qt.AlignHCenter)
		
		#entry_box2=QtGui.QGroupBox("Entries")
		self.btn_entry_back2=QtGui.QPushButton("Back")
		self.btn_entry_next2=QtGui.QPushButton("Next")
		self.btn_entry_update=QtGui.QPushButton("Update / Save Edited")



		self.btn_entry_back2.setEnabled(False)		

		entry_layout2=QtGui.QHBoxLayout()
		#entry_layout2.addWidget(entry_box2)

		entry_layout2=QtGui.QHBoxLayout()
		entry_layout2.addWidget(self.btn_entry_back2)
		entry_layout2.addWidget(self.btn_entry_next2)
		
		self.connect(self.btn_entry_back2,QtCore.SIGNAL('clicked()'),self.editor_back)
		self.connect(self.btn_entry_next2,QtCore.SIGNAL('clicked()'),self.editor_next)
		self.connect(self.btn_entry_update,QtCore.SIGNAL('clicked()'),self.update_entry)
		
		self.mainwidget_editor2=QtGui.QWidget(self)  #Qwidget for edit page2
		
		tab_editor_grid=QtGui.QGridLayout()

		vertical_editor_layout2=QtGui.QVBoxLayout()
		
				
		for i in range(12,23):
			lbl=QtGui.QLabel(self.fileddata[i][0])
			
			textedit=QtGui.QLineEdit("")
			
			exec("self.%s = textedit" %(self.fileddata[i][1]+'_edit'))

			tab_editor_grid.addWidget(lbl,i,0)
			tab_editor_grid.addWidget(textedit,i,1)
			
			i=i+1
		
		
		vertical_editor_layout2.addWidget(content_page2_label)
		vertical_editor_layout2.addLayout(tab_editor_grid)
		vertical_editor_layout2.addLayout(entry_layout2) ## QGroupBox  ---Need EXTENSIONto Next button
		vertical_editor_layout2.addWidget(self.btn_entry_update)		
		vertical_editor_layout2.addStretch(1)
		vertical_editor_layout2.setSpacing(10)
		
		
		self.mainwidget_editor2.setLayout(vertical_editor_layout2)		
		
	
	def add_list(self):
		  ####################      add to list

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		
		self.listing.preview.extend([str(self.entryno[0])])
		self.listing.listbox.addItem(db[str(self.entryno[0])][1])
		self.statusmessage("Adding List Success !")
		


	def homepage_function(self):
		if self.widget!='main':
			self.tabwidget.removeTab(0)	
			self.tabwidget.removeTab(0)					
			self.tabwidget.addTab(self.main_firstshown,"         ") #Add Main Page Home
			if self.widget==0:
				self.homesize=(int(self.geometry().width()),int(self.geometry().height()))
		
			self.widget='main'
			


	def list_menu_function(self):
		if self.widget!='list':
			self.tabwidget.removeTab(0)	
			self.tabwidget.removeTab(0)
			self.listing.loadrange()					
			self.tabwidget.addTab(self.listing,"List Page") #Add list tab
			self.widget='list'
			self.listing.loadrange()


	def add_menu_function(self):
		
		if self.widget!='add':
			self.tabwidget.removeTab(0)	
			self.tabwidget.removeTab(0)
			self.title.setText("<h1>%s</h1>" %shelve.open('settings','c')['schoolname'])					
			self.tabwidget.addTab(self.mainwidget,"Page1") #Add page 1 tab
			self.tabwidget.addTab(self.mainwidget_part,"Page2") #Add page 2 tab
			self.widget='add'

	def editor_menu_function(self):
		

		if self.widget!='editor':
			self.tabwidget.removeTab(0)	
			self.tabwidget.removeTab(0)					
			self.tabwidget.addTab(self.mainwidget_editor,"Page 1 editor") #Add page 1 tab
			self.tabwidget.addTab(self.mainwidget_editor2,"Page 2 editor") #Add page 2 tab
			self.widget='editor'
			self.dataloader_editer()
	

	def dataloader_editer(self):
		
		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		self.entryno_last=len(db.keys()) -1

		
		try:
			for i in range(23):
				eval("self.%s.setText(db[str(self.entryno[0])][i])" %(self.fileddata[i][1]+'_edit'))
			


			if self.entryno_last==self.entryno[0]:
				self.btn_entry_next.setEnabled(False)
				self.btn_entry_next2.setEnabled(False)
			else:
				self.btn_entry_next.setEnabled(True)
				self.btn_entry_next2.setEnabled(True)


			if self.entryno[0]==1:
				self.btn_entry_back.setEnabled(False)	
				self.btn_entry_back2.setEnabled(False)	
			else:
				self.btn_entry_back.setEnabled(True)	
				self.btn_entry_back2.setEnabled(True)	
		except:
			
			self.btn_entry_back.setEnabled(False)	
			self.btn_entry_back2.setEnabled(False)
			self.btn_entry_next.setEnabled(False)
			self.btn_entry_next2.setEnabled(False)
			for i in range(23):
				eval("self.%s.setText('')" %(self.fileddata[i][1]+'_edit'))


			
	def editor_next(self):
		
		self.entryno[0] = self.entryno[0] + 1	
		self.dataloader_editer()
		self.btn_entry_back.setEnabled(True)
		self.btn_entry_back2.setEnabled(True)
		if self.entryno_last==self.entryno[0]:
			self.btn_entry_next.setEnabled(False)
			self.btn_entry_next2.setEnabled(False)
			

	def editor_back(self):
		self.entryno[0] = self.entryno[0] -1
		self.dataloader_editer()
		self.btn_entry_next.setEnabled(True)
		self.btn_entry_next2.setEnabled(True)

		if self.entryno[0]==1:
			self.btn_entry_back.setEnabled(False)	
			self.btn_entry_back2.setEnabled(False)	



	def popup_search(self):
		self.popup1 = QtGui.QFrame(self,QtCore.Qt.Popup)
		self.popup1.setFrameStyle(QtGui.QFrame.WinPanel|QtGui.QFrame.Raised)
		self.popup1.resize(210,130)
		lblp=QtGui.QLabel("<h4>Enter match string  <br />to search</h4>",self.popup1)
		lblp.setAlignment(QtCore.Qt.AlignHCenter)
		lblp.setGeometry(25,3,130,30)
		
		self.search_box = QtGui.QLineEdit(self.popup1)
		self.connect(self.search_box,QtCore.SIGNAL('returnPressed()'),self.do_search)
		self.search_box.setGeometry(10,40,180,30)
				
		self.search_box.setFocus()
		tmpB = QtGui.QPushButton('Go',self.popup1)
		self.connect(tmpB,QtCore.SIGNAL('clicked()'),self.do_search)
		tmpB.setGeometry(37,90,130,30)
		


	def searchbar(self):
		self.popup_search()
		self.popup1.move( QtGui.QWidget.mapToGlobal(self,self.btn_entry_search.geometry().bottomLeft()))
		self.popup1.show()


	def do_search(self):

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		searchkey=str(self.search_box.text()).lower()
		found=False
		
		for entryid in range(1,(self.entryno_last+1)):
			for j in range(23):
				if searchkey in db[str(entryid)][j].lower():
					found=True
			if found==True:
				self.entryno[0]=entryid
				self.dataloader_editer()
				self.popup1.close()
				break
				
		if found==False:
			QtGui.QMessageBox.warning(self,"Not found", "Entry not found. Try using other keywords too" ,"Ok")	
			

	def update_entry(self):
		reply=QtGui.QMessageBox.question(self,"Confirmation", "Do you want to update current modification to the database ?",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
		if reply==QtGui.QMessageBox.Yes:
			self.storage_edit()
			

	def storage_edit(self):
		status_no=0
		status_no=len(shelve.open(shelve.open('settings','c')['DB'],'c').keys()) - 1 # Find entry no
		

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		self.student_prof=[]

		blank=0

		for i in range(23):
			text=str(eval("self.%s.text()" %(self.fileddata[i][1]+'_edit')))
			if text.isspace() or text=='':
				blank=1

		if blank==1:
			QtGui.QMessageBox.warning(self,"Partial filling", "You haven't completed filling all the fields" ,"Ok")

		else:
			for i in range(23):
				text=str(eval("self.%s.text()" %(self.fileddata[i][1]+'_edit')))
				self.student_prof.append(text)
										
			db[str(self.entryno[0])]=self.student_prof
			db.close()
		
			

			self.statusmessage("Update Succesfull")

		
				
			
class printlist(QtGui.QWidget):
	def __init__(self):
		QtGui.QWidget.__init__(self,None)

		self.preview=[]
		self.printlist = QtGui.QGroupBox("Admission No List")
		self.addrange = QtGui.QGroupBox("Add Range to List")

		self.remove_btn = QtGui.QPushButton("&Remove")
		self.clear_btn = QtGui.QPushButton("&Clear")
		self.preview_btn = QtGui.QPushButton("&Preview")
		self.print_btn = QtGui.QPushButton("Pri&nt")	
		self.rough_preview_btn = QtGui.QPushButton("Rough Preview")
		self.rough_print_btn = QtGui.QPushButton("Rough Print")		
	
		self.add_btn=  QtGui.QPushButton("Add")	

		self.connect(self.add_btn,QtCore.SIGNAL('clicked()'),self.additem)
		self.connect(self.remove_btn,QtCore.SIGNAL('clicked()'),self.removeitem)
		self.connect(self.clear_btn,QtCore.SIGNAL('clicked()'),self.clearlist)
		self.connect(self.preview_btn, QtCore.SIGNAL('clicked()'),self.print_preview)
		self.connect(self.print_btn, QtCore.SIGNAL('clicked()'),self.print_)
		self.connect(self.rough_preview_btn, QtCore.SIGNAL('clicked()'),self.rough_print_preview)
		self.connect(self.rough_print_btn, QtCore.SIGNAL('clicked()'),self.rough_print_)

		self.add_btn.setMaximumHeight(35)

		from_lbl = QtGui.QLabel("      <-- Adm No -->")
		from_lbl.setMaximumHeight(20)
		
		to = QtGui.QLabel("    to")
		self.from_combo = QtGui.QComboBox()
		self.to_combo = QtGui.QComboBox()

		self.listbox = QtGui.QListWidget()
		self.listbox.setMaximumWidth(200)
		
		vlayout_listbox=QtGui.QVBoxLayout()
		hlayout_listbox=QtGui.QHBoxLayout()
		lbl1=QtGui.QLabel("")

		lbl4=QtGui.QLabel("")

		vlayout_listbox.addWidget(self.remove_btn)
		vlayout_listbox.addWidget(self.clear_btn)
		vlayout_listbox.addWidget(lbl1)
		vlayout_listbox.addWidget(self.rough_preview_btn)
		vlayout_listbox.addWidget(self.rough_print_btn)
		vlayout_listbox.addWidget(lbl4)
		vlayout_listbox.addWidget(self.preview_btn)
		vlayout_listbox.addWidget(self.print_btn)

		hlayout_listbox.addWidget(self.listbox)
		hlayout_listbox.addLayout(vlayout_listbox)
		self.printlist.setLayout(hlayout_listbox)


		h1layout_range=QtGui.QHBoxLayout()
		h2layout_range=QtGui.QHBoxLayout()
		h3layout_range=QtGui.QHBoxLayout()
		v1layout_range=QtGui.QVBoxLayout()

		lbl5=QtGui.QLabel("")	
		lbl6=QtGui.QLabel("")
		lbl7=QtGui.QLabel("")
		lbl7.setMaximumHeight(20)
		rect=QtGui.QLabel("")
		rect.setMinimumHeight(80)

		h1layout_range.addWidget(from_lbl)
		

		h2layout_range.addWidget(self.from_combo)
		h2layout_range.addWidget(to)
		h2layout_range.addWidget(self.to_combo)

		h3layout_range.addWidget(self.add_btn)

		v1layout_range.addLayout(h1layout_range)
		v1layout_range.addLayout(h2layout_range)
		v1layout_range.addWidget(lbl7)
		v1layout_range.addLayout(h3layout_range)
		v1layout_range.addWidget(rect)
		
		self.addrange.setLayout(v1layout_range)

		Hlayout=QtGui.QHBoxLayout()
		Hlayout.addWidget(self.printlist)
		Hlayout.addWidget(self.addrange)
		self.setLayout(Hlayout)


		self.loadrange()
		
		self.preview_window=prev(self,self.preview) # preview class and window
		self.preview_window.hide()

		self.rough_preview_window=rough_prev(self,self.preview) # rough preview class and window
		self.rough_preview_window.hide()
	
	def loadrange(self):

		handle=shelve.open(shelve.open('settings','c')['DB'],'c')

		entrynos = []
		for i in handle.keys():
			if type(handle[i])==list:
				entrynos.append(handle[i][0])
		entrynos.sort()

		self.from_combo.clear()
		self.to_combo.clear()
		self.from_combo.addItems(QtCore.QStringList(entrynos))
		self.to_combo.addItems(QtCore.QStringList(entrynos))

	def getid(self,combotxt):
		handle=shelve.open(shelve.open('settings','c')['DB'],'c')
		for i in handle.keys():
			if handle[i][0]==combotxt:
				return i	
	
	def additem(self):
		range_ = []

		for i in range(int(self.getid(self.from_combo.currentText())),int(self.getid(self.to_combo.currentText())) +1):
			range_.append(str(i))

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		
		self.preview.extend(range_)

		for i in range_:
			self.listbox.addItem(db[i][1])
		self.loadrange()		
		

	def removeitem(self):
		
		self.listbox.takeItem(self.listbox.currentRow())
		del self.preview[self.listbox.currentRow()]

	def clearlist(self):
		self.listbox.clear()
		self.preview=[]


	def print_preview(self):
		
		self.preview_window.update(self.preview)
		self.preview_window.show()


	def rough_print_preview(self):
		
		self.rough_preview_window.update(self.preview)
		self.rough_preview_window.show()


    	def print_(self):
		
		
		self.preview_window.update(self.preview)
        	document = self.preview_window.prevbox.document()
        	printer = QtGui.QPrinter()

        	dlg = QtGui.QPrintDialog(printer, self)
        	if dlg.exec_() != QtGui.QDialog.Accepted:
            		return

        	document.print_(printer)
        

    	def rough_print_(self):
		
		
		self.rough_preview_window.update(self.preview)
        	document = self.rough_preview_window.prevbox.document()
        	printer = QtGui.QPrinter()

        	dlg = QtGui.QPrintDialog(printer, self)
        	if dlg.exec_() != QtGui.QDialog.Accepted:
            		return

        	document.print_(printer)

		
		

class prev(QtGui.QDialog):
	def __init__(self,parent,admlist):	
		QtGui.QDialog.__init__(self,parent)
		self.setWindowTitle("Print Preview")

		self.setWindowIcon(QtGui.QIcon("pics/logo.png"))

		screen=QtGui.QDesktopWidget().screenGeometry()
		self.resize(screen.width(),screen.height())

		self.prevbox=QtGui.QTextBrowser(self)
		
		
		self.prevbox.setHtml(self.generate_preview(admlist))
		layout=QtGui.QHBoxLayout()
		layout.addWidget(self.prevbox)
		self.setLayout(layout)

	def generate_preview(self,admlist):


		self.fileddata=filedata

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		html_head="<html> <title> Student Admission Register </title> \
		      <body> <h2><font> <br /><p align='center'>%s <br>Student Admission Register</p> </font></h2><p> <hr /> </p>" %shelve.open('settings','c')['schoolname']
		for i in admlist:
			html_head=html_head + '<table>'
			k=0
			for j in self.fileddata:
				html_head=html_head + '<tr><td> %s </td><td> %s </td><tr> ' %(j[0],db[i][k])
				k=k+1
			html_head=html_head + '</table><p> <hr /> </p>'

		html_head=html_head + '</body></html>'
		return(html_head)

	def update(self,content_list):
		self.prevbox.setHtml(self.generate_preview(content_list))





class rough_prev(QtGui.QDialog):
	def __init__(self,parent,admlist):	
		QtGui.QDialog.__init__(self,parent)

		self.setWindowIcon(QtGui.QIcon("pics/logo.png"))

		self.setWindowTitle("Rough Print Preview")
		screen=QtGui.QDesktopWidget().screenGeometry()
		self.resize(screen.width(),screen.height())

		self.prevbox=QtGui.QTextBrowser(self)
		
		
		self.prevbox.setHtml(self.generate_preview(admlist))
		layout=QtGui.QHBoxLayout()
		layout.addWidget(self.prevbox)
		self.setLayout(layout)

	def generate_preview(self,admlist):


		self.fileddata=filedata

		db = shelve.open(shelve.open('settings','c')['DB'], "c")
		html_head="<html> <title> Student Admission Register </title> \
		      <body> <h2><font> <br /><p align='center'>%s <br>Student Admission Register</p> </font></h2><p> <hr /> </p>" %shelve.open('settings','c')['schoolname']
		for i in admlist:
			
			k=0
			for j in self.fileddata:
				html_head=html_head + '%s, &nbsp;&nbsp;&nbsp;' %(db[i][k])
				k=k+1
			html_head=html_head + '<br /> <br />'

		html_head=html_head + '</body></html>'
		return(html_head)

	def update(self,content_list):
		self.prevbox.setHtml(self.generate_preview(content_list))


class about(QtGui.QDialog):

	def __init__(self):
		QtGui.QDialog.__init__(self)
			
		self.setWindowTitle("About School Admin..")
		self.resize(300,300)
		self.setWindowIcon(QtGui.QIcon("pics/logo.png"))

	


		lbl1=QtGui.QLabel("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src='pics/logo.png'> <h2>School Admin</h2> \
		<h4>Version 1.0 - beta</h4> \
		Copyright (c) 2007 Sarath Lakshman <br> \
		_____________________________________________________________________ <br /> \
		License : GNU General Public License V.3 <br /> \
		<h4> Developed by Sarath Lakshman</h4> \
		e-mail: sarathlakshman@slynux.org <br /> His blog: <a href='http://www.sarathlakshman.info'>www.sarathlakshman.info</a> <p> \
		<b>Project Homepage : <a href='http://school-admin-project.slynux.org'>http://school-admin-project.slynux.org</b></a></p>")
		lbl1.setAlignment(QtCore.Qt.AlignHCenter)


		
		lbl1.setFrameStyle(QtGui.QFrame.StyledPanel)
		lbl1.setStyleSheet("background-color:white;")

		vbox=QtGui.QVBoxLayout()
		vbox.addWidget(lbl1)
	
		self.setLayout(vbox)

		

		
app=QtGui.QApplication([])
px=QtGui.QPixmap("pics/splash.png")
splash=QtGui.QSplashScreen(px)
splash.show()
splash.showMessage("Loading modules",QtCore.Qt.AlignBottom)
window=thestudent_app()
splash.showMessage("Initiating startup",QtCore.Qt.AlignBottom)
window.show()
splash.finish(window)

sys.exit(app.exec_())
		
